package cn.itsource.pethome.order.service.impl;


import cn.itsource.pethome.basic.service.impl.BaseServiceImpl;
import cn.itsource.pethome.basic.util.CodeGenerateUtils;
import cn.itsource.pethome.basic.util.DistanceUtil;
import cn.itsource.pethome.basic.util.Point;
import cn.itsource.pethome.order.domain.OrderAddress;
import cn.itsource.pethome.order.domain.ProductOrder;
import cn.itsource.pethome.order.domain.ProductOrderDetail;
import cn.itsource.pethome.order.domain.UserAddress;
import cn.itsource.pethome.order.mapper.OrderAddressMapper;
import cn.itsource.pethome.order.mapper.ProductOrderDetailMapper;
import cn.itsource.pethome.order.mapper.ProductOrderMapper;
import cn.itsource.pethome.order.mapper.UserAddressMapper;
import cn.itsource.pethome.order.service.IProductOrderService;
import cn.itsource.pethome.org.domain.Shop;
import cn.itsource.pethome.org.mapper.ShopMapper;
import cn.itsource.pethome.pay.constant.PayConstants;
import cn.itsource.pethome.pay.domain.PayBill;
import cn.itsource.pethome.pay.service.IPayBillService;
import cn.itsource.pethome.product.domain.Product;
import cn.itsource.pethome.product.mapper.ProductMapper;
import cn.itsource.pethome.quartz.domain.QuartzJobInfo;
import cn.itsource.pethome.quartz.service.IQuartzService;
import cn.itsource.pethome.user.domain.User;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *宠物service层
 */
@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {
    //用户地址mapper
    @Autowired
    private UserAddressMapper userAddressMapper;
    //订单地址mapper
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    //产品服务地址mapper
    @Autowired
    private ProductMapper productMapper;
    //商店地址mapper
    @Autowired
    private ShopMapper  shopMapper;
    //订单mapper
    @Autowired
    private ProductOrderMapper productOrderMapper;
    //订单详情mapper
    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;
    //支付订单service
    @Autowired
    private IPayBillService payBillService;
    //定时任务service
    @Autowired
    private IQuartzService quartzService;



    /**
     * 提交订单
     *
     * @param param
     */
    @Override
    @Transactional
    public String submitOrder(Map<String, Object> param,User user) {//param  包含   addressId: 1, payType: 3 支付宝支付   products: [{id: 16, num: 1}, {id: 66, num: 2}]
       //获取用户地址
        Integer addressId = (Integer) param.get("addressId");
        //获取物品
        List<Map<String,Object>> products = (List<Map<String, Object>>) param.get("products");
        //获取支付方式
        Integer payType = (Integer) param.get("payType");
        //获取用户地址，通过用户地址id
        UserAddress userAddress = userAddressMapper.loadById(Long.valueOf(addressId));//写SQL
        //获取用户地址
        String fullAddress = userAddress.getFullAddress();
        //获取经纬度
        Point point = DistanceUtil.getPoint(fullAddress);
        //获取门店信息
        Shop shop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());//写SQL
        //宠物订单
        ProductOrder productOrder = createProductOrder(products,shop,payType,user);
        //保存订单
        productOrderMapper.save(productOrder);

        //设置产品服务详情
        ProductOrderDetail productOrderDetail = createProductOrderDetail(products,productOrder);
        //保存订单详情
        productOrderDetailMapper.save(productOrderDetail);

        //设置订单地址,传入用户id
        OrderAddress orderAddress = createOrderAddress(Long.valueOf(addressId),productOrder);
        //保存订单地址
        orderAddressMapper.save(orderAddress);

        //创建支付订单
        PayBill payBill = createPayBill(productOrder);
        //保存支付订单
        payBillService.save(payBill);

        //获取到支付宝的返回界面
        String formHtml = payBillService.goPay(payBill);

        //添加定时任务
        //返回QuartzJobInfo对象
        QuartzJobInfo quartzJobInfo = createQuartz(productOrder);
        //调用添加定时器
        quartzService.addJob(quartzJobInfo);

        //返回二维码界面form表单
        return formHtml;
    }

    /**
     * 创建定时任务
     * @param productOrder 订单
     * @return
     */
    private QuartzJobInfo createQuartz(ProductOrder productOrder) {
        //创建quartzJobInfo对象
        QuartzJobInfo quartzJobInfo = new QuartzJobInfo();
        //设置执行时间
        quartzJobInfo.setFireDate(productOrder.getLastPayTime());
        //设置job名字
        quartzJobInfo.setJobName(PayConstants.BUSINESSTYPE_PRODUCT+productOrder.getId());
        //创建map集合
        Map<String, Object> param = new HashMap<>();
        //添加
        param.put("orderSn",productOrder.getOrderSn());
        //设置参数
        quartzJobInfo.setParams(param);
        //设置类型
        quartzJobInfo.setType(PayConstants.BUSINESSTYPE_PRODUCT);
        //返回对象
        return quartzJobInfo;
    }

    /**
     * 创建支付订单
     * @return
     */
    private PayBill createPayBill(ProductOrder productOrder) {
        //创建支付订单对象
        PayBill payBill = new PayBill();
        /**摘要*/
        payBill.setDigest(productOrder.getDigest());
        /**金额*/
        payBill.setMoney(productOrder.getPrice());
        /**订单编号*/
        payBill.setOrderSn(productOrder.getOrderSn());
        /**状态  0 待支付 1 支付完成  -1 取消*/
        payBill.setState(0);
        /**最后支付时间*/
        payBill.setLastPayTime(payBill.getLastPayTime());
        /**0 余额 1 支付宝 2 微信 3 银联*/
        payBill.setPayChannel(productOrder.getPayType());
        /**业务类型*/
        payBill.setBusinessType(PayConstants.BUSINESSTYPE_PRODUCT);
        /**业务键*/
        payBill.setBusinessKey(productOrder.getId());
        /**用户*/
        payBill.setUser(productOrder.getUser());
        /**店铺*/
        payBill.setShop(productOrder.getShop());
        return payBill;
    }

    /**
     * 产品服务详情
     * @param products 产品服务
     * @param productOrder 订单
     * @return
     */
    private ProductOrderDetail createProductOrderDetail(List<Map<String, Object>> products, ProductOrder productOrder) {
        //创建订单详情对象
        ProductOrderDetail productOrderDetail = new ProductOrderDetail();
        //循环遍历传入的产品集合
        for (Map<String, Object> param : products) {
            //获取每个服务产品的id
            Integer id = (Integer) param.get("id");
            //获取每个服务产品的数量
            Integer num = (Integer) param.get("num");
            //设置产品
            productOrderDetail.setProduct(productMapper.loadById(Long.valueOf(id)));
            //设置订单
            productOrderDetail.setOrder(productOrder);
            //设置销售数量
            productOrderDetail.setSalecount(num);
            //设置创建时间
            productOrderDetail.setCreatetime(new Date());
        }
        //返回订单详情对象
        return productOrderDetail;
    }

    /**
     * 创建订单
     *
     * @param
     */
    private ProductOrder createProductOrder(List<Map<String, Object>> products,
                                            Shop shop,Integer payType,User user) {
        //创建订单对象
        ProductOrder productOrder = new ProductOrder();
        //摘要大苏打
        productOrder.setDigest("[服务订单]购买" + shop.getName() + "商铺对应的服务！！");
        //状态   待支付0 待消费1 待确认2 完成3 取消-1
        productOrder.setState(0);
        //支付方式
        productOrder.setPayType(payType);
        //订单编号
        productOrder.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        //支付订单号
        productOrder.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        //最后支付时间new Date(System.currentTimeMillis() + 30*60*1000)
        productOrder.setLastPayTime(DateUtils.addSeconds(new Date(), 120));
        //用户
        productOrder.setUser(user);
        //店铺
        productOrder.setShop(shop);

        //总金额
        BigDecimal totalPrice = new BigDecimal(0);
        for (Map<String, Object> param : products) {
            //获取每个服务产品的id
            Integer id = (Integer) param.get("id");
            //获取每个服务产品的数量
            Integer num = (Integer) param.get("num");
            //根据id进行查询，获取价格
            Product product = productMapper.loadById(Long.valueOf(id));//写sql
            //获取售价
            BigDecimal saleprice = product.getSaleprice();
            //获取每个商品的总价格,循环添加，并赋值
            totalPrice = totalPrice.add(saleprice.multiply(new BigDecimal(num)));
        }
        //价格
        productOrder.setPrice(totalPrice);
        //返沪订单对象
        return productOrder;
    }

    /**
     * 设置订单地址
     * @return
     */
    private OrderAddress createOrderAddress(Long addressId,ProductOrder productOrder) {
        //查询用户地址,根据id查询用户地址
        UserAddress userAddress =  userAddressMapper.loadById(addressId);
        //创建订单地址对象
        OrderAddress orderAddress = new OrderAddress();
        //使用beanUtils工具的copy方法  ，将用户地址设置进订单地址
        BeanUtils.copyProperties(userAddress, orderAddress);
        //对应服务订单
        orderAddress.setOrder(productOrder);
        //订单编号
        orderAddress.setOrderSn(productOrder.getOrderSn());
        //返回订单对象
        return orderAddress;
    }
}
